package com.example.project.config;


import com.example.project.entity.ResponseInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

//@WebFilter(urlPatterns="/*")
public class TokenFilter implements Filter {
    private List<String> urlArr= Arrays.asList("/user/login","/user/sss","/system/aaa","/avatar");

    private boolean checkUrl(String curUrl){
        for (String s : urlArr) {
            if(curUrl.indexOf(s)>=0){
                return  true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;

        String requestURI = request.getRequestURI();
        System.out.println(requestURI);


        String token = request.getHeader("Token");
        if(checkUrl(requestURI)||StringUtils.hasLength(token)){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            ResponseInfo res = ResponseInfo.fail(401, "用户无权限");
            ObjectMapper mapper = new ObjectMapper();
            String resStr = mapper.writeValueAsString(res);
            response.getWriter().write(resStr);
        }

    }
    }
